package elicecn.swing.watermarker;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.TransferHandler;

public class FilePathTransferHandler extends TransferHandler {
	private static final long serialVersionUID = -1012593250324056346L;
	private DataFlavor files;
	private Watermark watermark;

	public FilePathTransferHandler(Watermark watermark) {
		this.watermark = watermark;
		files = DataFlavor.javaFileListFlavor;
	}

	@Override
	public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
		for (DataFlavor dataFlavor : transferFlavors) {
			if (dataFlavor.equals(files)) {
				return true;
			}
		}
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean importData(JComponent c, Transferable t) {
		try {
			if (canImport(null, t.getTransferDataFlavors())) {
				List fileList = (List) t.getTransferData(files);
				if (fileList.size() != 1) {
					JOptionPane.showMessageDialog(watermark, "只能验证一个文件的水印信息！",
							"错误", JOptionPane.ERROR_MESSAGE);
					return false;
				}
				for (int i = 0; i < fileList.size(); i++) {
					File file = (File) fileList.get(i);
					if (file.isFile()) {
						watermark.filePath.setText(file.getCanonicalPath());
						watermark.generateAll.doClick();
					} else {
						JOptionPane.showMessageDialog(watermark,
								"只有文件才能生成水印信息。", "错误",
								JOptionPane.ERROR_MESSAGE);
						return false;
					}
				}
				return true;
			}
		} catch (UnsupportedFlavorException ufe) {
			System.out.println("importData: unsupported data flavor");
		} catch (IOException ieo) {
			System.out.println("importData: I/O exception");
		}
		return false;
	}
}
